// @algorithm @lc id=230 lang=cpp 
// @title kth-smallest-element-in-a-bst


// #define print(...)
// @test([3,1,4,null,2],1)=1
// @test([5,3,6,2,4,null,null,1],3)=3
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode*> stk;
        while(root || stk.size()){
            while(root){
                stk.push(root);
                root = root->left;
            }
            root = stk.top(); stk.pop();
            if(0 == --k) break;
            root = root->right;
        }
        return root->val;
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */